package com.polaris.live.manager

import com.polaris.live.common.constant.CacheConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst.LOAD_FILE_PAG
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.LogExt
import com.polaris.live.resp.back_resp.AreaCodeResp
import com.polaris.live.resp.back_resp.LanguageResp
import com.polaris.live.resp.back_resp.TranslationResp
import com.polaris.live.utils.file.FileUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Locale

/**
 * AssessConfigManager
 *
 * @author Created by lucas on 2023/10/26 21:07
 */
object AssetsConfigManager {

    private const val AREA_CODE_NAME = "area.json"
    private const val LANGUAGE_NAME = "language.json"
    private const val TRANSLATION_NAME = "translation.json"
    private const val SYSTEM_LANGUAGE_NAME = "system_language.json"


    /**
     * 初始化区号
     */
    fun initAllAreaCode() {
        GlobalScope.launch(CoroutineScopeManager.defaultDispatcher) {
            if (getAreaCode(Locale.ENGLISH.country) == null) {
                fetchAreaCodeAndSave()
            }
            LogExt.logI("--init", "initAllAreaCode success")
        }
        initLanguageResps()
    }

    suspend fun fetchAreaCodeAndSave(): List<AreaCodeResp> {
        return fetchAreaCodes().apply {
            val kv = MMKV.mmkvWithID(CacheConst.APP)
            forEach {
                kv.encode(CacheConst.country + it.countryCode, it)
            }
        }
    }

    /**
     * 读取assets下的所有code信息
     */
    suspend fun fetchAreaCodes(): List<AreaCodeResp> {
        val json = FileUtils.readAssetsText(AREA_CODE_NAME)
        return JsonUtils.fromJson<List<AreaCodeResp>>(json)
            ?.let { list ->
                val banAreaCodes = getBanAreaCodes()

                list.filter { !banAreaCodes.contains(it.areaCode) }
            }
            ?.onEach {
                it.firstLetter = it.countryName?.get(0)?.toString()
            }
            ?: emptyList()
    }

    suspend fun getCountryAreaCodes(): List<AreaCodeResp> {
        val json = FileUtils.readAssetsText(AREA_CODE_NAME)
        val list = JsonUtils.fromJson<MutableList<AreaCodeResp>>(json) ?: mutableListOf()
        //因为图片展示是直接用本地图片，所以url就不需要了
        list.add(AreaCodeResp("880", "BD", "Bangladesh", ""))
        return list
    }


    private var _banAreaCodes: Set<String>? = null
    private fun getBanAreaCodes(): Set<String> {
        return _banAreaCodes ?: let {
            (AppConfigManager.getConfig(CommonConst.Configs.banAreaCodes)?.let {
                JsonUtils.fromJson<Set<String>>(it)
            } ?: emptySet()).apply {
                _banAreaCodes = this
            }
        }
    }

    /**
     * 初始化那些需要先放到文件里用的pag动画
     */
    fun assetsLoadFilePag() {
        GlobalScope.launch(CoroutineScopeManager.defaultDispatcher) {
            FileUtils.saveAssetsDir(
                LOAD_FILE_PAG,
                FileUtils.getAssetsToFile() + "/$LOAD_FILE_PAG"
            )
        }
    }

    /**
     * 根据国家号码获取手机区号
     */
    fun getAreaCode(countryCode: String): AreaCodeResp? {
        val kv = MMKV.mmkvWithID(CacheConst.APP)
        return kv.decodeParcelable(CacheConst.country + countryCode, AreaCodeResp::class.java)
    }


    /**
     * 读取assets下的所有language信息
     */
    private var LanguageResps: List<LanguageResp>? = null
    fun fetchLanguage(): List<LanguageResp>? {
        return LanguageResps ?: run {
            initLanguageResps()
            null
        }
    }

    private fun initLanguageResps() {
        GlobalScope.launch(CoroutineScopeManager.defaultDispatcher) {
            //初始化本地语言对应数据
            val json = FileUtils.readAssetsText(LANGUAGE_NAME)
            LanguageResps = JsonUtils.fromJson(json) ?: emptyList()
        }
    }

    /**
     * 读取assets下的所有translation语言
     */
    suspend fun readTranslation(): List<TranslationResp> {
        val json = FileUtils.readAssetsText(TRANSLATION_NAME)
        return JsonUtils.fromJson(json) ?: emptyList()
    }

    /**
     * 读取assets下的所system language信息
     */
    suspend fun systemLanguage(): List<LanguageResp> {
        val json = FileUtils.readAssetsText(SYSTEM_LANGUAGE_NAME)
        return JsonUtils.fromJson(json) ?: emptyList()
    }

    fun initResourceSDK() {
        GlobalScope.launch(CoroutineScopeManager.defaultDispatcher) {
            copyToResourceSDK()

            LogExt.logI("--init", "initResourceSDK success")
        }
    }

    private suspend fun copyToResourceSDK() {
        FileUtils.saveAssetsDir("models", FileUtils.getBeautyDir() + "/models")
        FileUtils.saveAssetsDir(
            "MagicEngine.bundle",
            FileUtils.getBeautyDir() + "/MagicEngine.bundle"
        )
    }
}